import time

from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

from util.logger import AutomationLogger

timeout = 30
poll = 2


class WebTasks:
    def __init__(self, driver):
        self.driver = driver
        self.log_client = AutomationLogger()
        self.log_client.setUp()
        self.logger = self.log_client.logger

    def kw_search_in_baidu(self, search_keyword):

        self.driver.get("https://www.baidu.com")
        self.logger.info('打开浏览器，访问百度')

        elem = self._find_elem_by_name("wd")
        elem.send_keys(f'{search_keyword}{Keys.RETURN}')
        self.logger.info(f'搜索关键词~{search_keyword}')

        start = time.time()
        is_found = False
        while time.time() - start < timeout and not is_found:
            time.sleep(poll)
            is_found = True if f'{search_keyword}' in self.driver.title or '安全验证' in self.driver.title else False

        return is_found

    def _find_elem_by_name(self, name, time_out=timeout, raise_exception=True):
        start = time.time()
        elem = None
        while time.time() - start < time_out and elem is None:
            time.sleep(poll)
            try:
                elem = self.driver.find_element(By.NAME, name)
            except Exception:
                self.logger.debug('Element not found, waiting...')

        if elem is None and raise_exception:
            raise LookupError(f'The element which name is {name} could not be found')

        return elem
